package Interfaces;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.Border;

import Modelo.Modelo;

public class InterfaceCalcular extends JPanel{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextArea historico, previewFormula;
	private JScrollPane scrollHistorico, scrollPreview;
	private Border borderVisor;
	private JButton botaoOK, limpar;

	private Modelo _modelo;
	
	private JButton[] f;
	
	private int selected = -1;
	
	public InterfaceCalcular(Modelo modelo, JButton[] buttons) {
		f = buttons;
		
		_modelo = modelo;
		_modelo.setInterfaceCalcular(this);
		
		Dimension d = new Dimension(_modelo.getInterfacePrincipal().getSize());
		setSize(d);
		setPreferredSize(d);
		setMinimumSize(d);
		setMaximumSize(d);
		
		InicializeComponents();
		
		addComponents();
	}
	
	private void addComponents() {
		
		this.add(scrollHistorico);
		
		historico.setSize(315, 70);
		
		this.add(scrollPreview);
		
		this.add(limpar);
		
		limpar.setSize(50, 50);
		limpar.setPreferredSize(new Dimension(50, 50));
		limpar.setMaximumSize(new Dimension(50, 50));
		limpar.setMinimumSize(new Dimension(50, 50));
		
		this.add(botaoOK);
		
		botaoOK.setSize(52, 50);
		botaoOK.setPreferredSize(new Dimension(52, 50));
		botaoOK.setMaximumSize(new Dimension(52, 50));
		botaoOK.setMinimumSize(new Dimension(52, 50));
		

		for(int i = 0; i < 18; i++)
		{
			f[i].addActionListener(new PreviewCalculaListener(this, _modelo, i));
			
			this.add(f[i]);
		}
	}
	
	private void InicializeComponents() {
		
		setLayout(new FlowLayout());
		
		borderVisor=BorderFactory.createLineBorder(Color.BLACK);
		
		historico=new JTextArea("\n\tHistórico...", 5, 42);
		historico.setEditable(false); //<-- nao aceita input
		historico.setBorder(borderVisor);
		
		scrollHistorico = new JScrollPane(historico);
		scrollHistorico.setBorder(borderVisor);
		scrollHistorico.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		previewFormula=new JTextArea("\n\tPreview da Formula", 3, 31);
		previewFormula.setBorder(borderVisor);
		
		scrollPreview = new JScrollPane(previewFormula);
		scrollPreview.setBorder(borderVisor);
		scrollPreview.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
		
		botaoOK=new JButton("=");
		
		botaoOK.addActionListener(new CalculaListener(this));
		
		limpar = new JButton("CE");
		
		limpar.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e) 
			{
				historico.setText("\n\tHistórico...");
			}
		});
	}
	
	private class CalculaListener implements ActionListener
	{
		private InterfaceCalcular it;
		
		public CalculaListener(InterfaceCalcular it)
		{
			this.it = it;
		}
		
		@Override
		public void actionPerformed(ActionEvent e) 
		{
			if(selected != -1)
			{
				if(!_modelo.isVazio(selected))
				{
					if(historico.getText().contains("Histórico"))
						historico.setText("");
					
					_modelo.preparaFormula(selected);
	
					if(_modelo.tamanhoVars(selected) > 0)
					{
						String value;
						ArrayList<String> varNames = _modelo.getVariaveis(selected);
						
						for(int i = 0; i < varNames.size(); i++)
						{
							do
							{
								value = null;
								
								value = (String)JOptionPane.showInputDialog(it, 
																	"Variavel " + varNames.get(i) + ":", 
																	"Variaveis", 
																	JOptionPane.INFORMATION_MESSAGE);
								
								if(value != null) 
								{
									if(value.length() > 0)
									{
										int x;
										
										value = value.trim();
										
										for(x = 0; x < value.length(); x++)
											if(value.charAt(x) < '0' || value.charAt(x) > '9')	
												if(value.charAt(x) != '.' && value.charAt(x) != '-')
													if(value.charAt(x + 1) >= '0' && value.charAt(x + 1) <= '9')
														break;
											
											if(x == value.length())
											{
												_modelo.setVar(selected, Double.parseDouble(value), varNames.get(i));
												break;
											}
											else
												JOptionPane.showMessageDialog(it, 
														"So são aceites números.", 
														"Variaveis", 
														JOptionPane.WARNING_MESSAGE);
									}
									else
										JOptionPane.showMessageDialog(it, 
												"Digite um valor para a varivel.", 
												"Variaveis", 
												JOptionPane.WARNING_MESSAGE);
								}
								else
									return;
								
							}
							while(true);
						}
					}
					
					double resultado = _modelo.resolverEq(selected);
					
					String strResultado;
					
					if(resultado == resultado)
						strResultado = String.valueOf(resultado);
					else
						strResultado = "Impossivel de resolver. \n\n\tPode conter números complexos ou imaginários.";
					
					historico.setText(historico.getText() + "\t" + 
					_modelo.getEqNome(selected) + ":" + "\n\t\t" + strResultado + "\n");	
				}
				else
					JOptionPane.showMessageDialog(it, "È necessário atribuir uma formula ao botão.", "Aviso", JOptionPane.ERROR_MESSAGE);
			}
			else
				JOptionPane.showMessageDialog(it, "Tem que seleccionar um botão primeiro.", "Informaçãoo", JOptionPane.QUESTION_MESSAGE);
		}
	}

	public JTextArea getPreviewFormula()
	{
		return previewFormula;
	}
	
	public void setSelected(int index)
	{
		selected = index;
	}
	
}
